import Vue from "vue";
import VueRouter from "vue-pages";
import Home from "@/pages/Home.vue";
import GoodsList from "@/pages/GoodsList.vue";
import NewsList from "@/pages/NewsList.vue";
import My from "@/pages/My.vue";
import NoFound from "@/pages/NoFound.vue";
import Login from "@/pages/Login.vue";
import Index from "@/pages/Index.vue";
import Film from "@/pages/Film.vue";
Vue.use(VueRouter);
const router = new VueRouter({
	routes:[
		{
			path:"/",
			component:Index,
			children:[
				{
					// 有导航的
					path:"/",
					component:Home
				},{
					// 有导航的
					path:"/goodsList",
					name:"goods",
					meta:{
						isAuth:true,
						title:"商品信息，品质一流"
					},
					component:GoodsList
				},{
					// 有导航的
					path:"/newsList",
					name:"news",
					meta:{
						isAuth:true,
						title:"我是新闻，我是真新闻"
					},
					component:NewsList
				},{
					// 有导航的
					path:"/my",
					name:"my",
					meta:{
						isAuth:true
					},
					component:My,
					// beforeEnter 相当于 beforeRouteEnter，但是beforeEnter中使用next()没有回调函数
					// beforeEnter(to,from,next){
					// 	if(localStorage.getItem("username"))
					// 		next();
					// 	else{
					// 		next({
					// 			path:"/login",
					// 			query:{
					// 				returnUrl:to.fullPath
					// 			}
					// 		})
					// 	}
					// }
				},
			]
		},
		{
			path:"*",
			component:NoFound,
			name:"noFound"
		},{
			path:"/login",
			name:"login",
			component:Login,
		},{
			path:"/film",
			name:"film",
			component:Film
		}
	],
	mode:"history"
});
// 全局前置守卫
router.beforeEach(function(to,from,next){
	console.log("beforeEach",this)
	// console.log("to",to);
	// console.log("from",from);
	// console.log("next",next);
	const arr = ["goods","news","my"];
	// 判断权限
	// if(arr.includes(to.name)){
	if(to.meta.isAuth){
		if(localStorage.getItem("username")){
			next();
		}else{
			next({
				path:"/login",
				query:{
					returnUrl:to.fullPath
				}
			})
		}
	}else{
		next();
	}

});

// 全局后置守卫
router.afterEach(function(to,from,next){
	console.log("afterEach",this);
	// beforeCreate之前执行
	// console.log("afterEach");
	// next是undefined
	// console.log("to",to);
	// console.log("from",from);

	// 页面增加标题
	if(to.meta.title){
		document.title = to.meta.title
	}
})

// 全局解析守卫
router.beforeResolve(function(to,from,next){
	// 实例创建前执行
	console.log("beforeResolve",this);// 可以做一些异步的处理。 统一的AJAX请求

	// fetch()
	// console.log("beforeResolve->to",to)
	// console.log("beforeResolve->from",from)
	// console.log("beforeResolve->next",next);
	next();
})
export default router;